package com.xrit.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xrit.constant.MessageConstant;
import com.xrit.exception.CustomException;
import com.xrit.mapper.OrderMapper;
import com.xrit.mapper.SetMealMapper;
import com.xrit.pojo.Order;
import com.xrit.pojo.OrderExample;
import com.xrit.pojo.SetMeal;
import com.xrit.query.QueryPageBean;
import com.xrit.result.PageResult;
import com.xrit.service.SetMealService;
import com.xrit.utils.QiNiuUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SetMealServiceImpl implements SetMealService {

    @Autowired
    private SetMealMapper setMealMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private FreeMarkerConfig freeMarkerConfig;

    @Value("${out_put_path}")
    private String output;

    /**
     * 根据id获取套餐明细，携带检查组，检查项信息
     * @return
     */
    @Override
    public SetMeal findDetailsById(Integer id) {
        return setMealMapper.queryDetailsById(id);
    }

    /**
     * 获取套餐列表
     * @return
     */
    @Override
    public List<SetMeal> findAll() {
        return setMealMapper.selectByExample(null);
    }

    /**
     * 删除套餐
     * @param id
     * @throws CustomException
     */
    @Transactional
    @Override
    public void deleteById(Integer id) throws CustomException {
        //1.判断套餐是否被订单使用了
        OrderExample oe=new OrderExample();
        OrderExample.Criteria oec = oe.createCriteria();
        oec.andSetmealIdEqualTo(id);
        List<Order> orders = orderMapper.selectByExample(oe);

        if (orders!=null && orders.size()>0){
            //1.1 被使用了则不能删除,手动抛出异常
            throw new CustomException(MessageConstant.SETMEAL_IN_USE);
        }else{
            //1.2 没被使用，先解散，删除套餐和检查组的关系
            setMealMapper.deleteMealAndGroupByMealId(id);
            //1.3 再来删除套餐
            setMealMapper.deleteByPrimaryKey(id);
        }
    }

    /**
     * 修改套餐
     * @param meal
     * @param groupIds
     */
    @Override
    public void update(SetMeal meal, Integer[] groupIds) {
        //1.修改套餐基础数据
        setMealMapper.updateByPrimaryKeySelective(meal);
        //2.解除当前套餐和检查组的关系
        setMealMapper.deleteMealAndGroupByMealId(meal.getId());
        //3.添加和检查组的关系
        addSetMealAndCheckGroup(meal.getId(),groupIds);
    }

    /**
     * 根据mealid查询检查组
     * @param id
     * @return
     */
    @Override
    public List<Integer> findCheckGroupByMealId(Integer id) {
        return setMealMapper.queryCheckGroupByMealId(id);
    }

    /**
     * 通过id查询套餐信息
     * @param id
     * @return
     */
    @Override
    public SetMeal findById(Integer id) {
        return setMealMapper.selectByPrimaryKey(id);
    }

    @Transactional
    @Override
    public void addSetMeal(SetMeal setMeal, Integer[] groupIds) {
        //除了套餐的数据需要新增
        setMealMapper.insertSelective(setMeal);//需要修改SQL代码，返回id值
        //添加和检查组的关系
        addSetMealAndCheckGroup(setMeal.getId(),groupIds);

        //3.生成静态页面
        generateSetMealHTML();
    }

    private void generateSetMealHTML(){
        //3.1 生成套餐列表页面
        List<SetMeal> setMeals = setMealMapper.selectByExample(null);
        setMeals.forEach(s->{
            s.setImg(QiNiuUtils.DOMAIN+s.getImg());
        });
        //构建数据
        Map map=new HashMap();
        map.put("setmealList",setMeals);
        String setmealListFile=output+"mobile_setmeal.html";
        generateHtml("mobile_setmeal.ftl",setmealListFile,map);
        //3.2 生成套餐详情页面

        generateSetMealDetailsHTML(setMeals);
    }

    private void generateSetMealDetailsHTML(List<SetMeal> setMeals){
        //3.1 生成套餐列表详情页面
        setMeals.forEach(s->{
            SetMeal meal = setMealMapper.queryDetailsById(s.getId());
            meal.setImg(s.getImg());
            //构建数据
            Map map=new HashMap();
            map.put("setmeal",meal);
            String setmealListFile=output+"mobile_setmeal_"+meal.getId()+".html";
            generateHtml("mobile_setmeal_detail.ftl",setmealListFile,map);
        });
    }


    public void addSetMealAndCheckGroup(Integer id,Integer[] groupIds){
        if (groupIds!=null && groupIds.length>0){
            setMealMapper.addSetMealCheckGroup(id,groupIds);
        }
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize(),true);
        // 有查询条件的处理, 模糊查询
        if(!StringUtils.isEmpty(queryPageBean.getQueryString())){
            // 拼接%
            queryPageBean.setQueryString("%" + queryPageBean.getQueryString()+ "%");
        }
        Page<SetMeal> page=setMealMapper.selectByQueryString(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 封装生成静态页面的方法
     * @param templateName  模板名称
     * @param outputPath    输出路径
     * @param map           模板数据
     */
    private void generateHtml(String templateName, String outputPath, Map<String,Object> map){
        //1.创建配置类
        Configuration configuration=freeMarkerConfig.getConfiguration();
        //2.加载模板
        Template template = null;
        BufferedWriter bw=null;
        try {
            template = configuration.getTemplate(templateName);
            //3.创建数据模型

            //4.创输出文件路径对象
            bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputPath),"utf-8"));
            //5.将数据填充到模板
            template.process(map, bw);
            //6.刷新缓冲流
            bw.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        } finally {
            //7.关闭Writer对象
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
